#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import shutil
import yaml



def src_clone(pkg_name, pkg_url,pkg_branch):
    command = "git clone --single-branch --branch {branch} {url} src/{name}".format(
        branch=pkg_branch, 
        url=pkg_url,
        name=pkg_name)
    print(command)
    os.system(command=command)
    return "src/{name}".format(name=pkg_name)

def packing_system():
    if os.path.exists("/usr/bin/apt"):
        return checkPackage
    elif os.path.exists("/usr/bin/dnf"):
        return "dnf"
    else:
        raise "no packing_system"

def checkPackage(pkg_name):
    import apt
    cache = apt.Cache()
    cache.update()
    cache.open()

    pkg = cache[pkg_name]
    if pkg.is_installed:
        print("{pkg_name} already installed".format(pkg_name=pkg_name))
    else:
        pkg.mark_install()
        cache.commit()

def set_build_env(pkgs : list, func=packing_system() ):
    for pkg in pkgs:
        func(pkg)

def build():
    if not os.path.exists("linux/.config"):
        shutil.copyfile("config-6.1.0-3-generic", "linux/.config")
    os.system("make -C linux bzImage")

def get_yaml_file():
    yaml_path = "config/"
    # yaml_file = "config/linux.yaml"
    for root,dirs,files in os.walk(yaml_path):
        #print(root)
        #print(dirs)
        print(files)
        for file in files:
            filename = os.path.join(yaml_path, file)
            with open(filename, 'r') as f:
                pkg = yaml.safe_load(f)
                src = src_clone(
                        pkg_name=pkg['Name'] + '-' + pkg['Version'],
                        pkg_url=pkg['Url'], 
                        pkg_branch=pkg['Branch']
                        )
                set_build_env(pkg['Build-Depends'])

    
    # print(pkg)
    # return pkg    

if __name__ == '__main__':
    '''
    pkg = get_yaml_file()
    src = src_clone(
        pkg_name=pkg['Name'] + '-' + pkg['Version'],
        pkg_url=pkg['Url'], 
        pkg_branch=pkg['Branch']
        )
    set_build_env(pkg['Build-Depends'])
    '''
    get_yaml_file()
    

